import calendar
import tkinter as tk
root = tk.Tk()

def LabelCal(Year, Month):
    labels = [['一', '二', '三', '四', '五', '六', '日']]
    # 首行放置“年、月”的位置
    label = tk.Label(root, text=str(Year) + "年")
    label.grid(row=0, column=2)
    label = tk.Label(root, text=str(Month) + "月")
    label.grid(row=0, column=4)
    mo = calendar.monthcalendar(Year, Month)
    #清空页面数据
    for r in range(7):
        for c in range(7):
           l = tk.Label(root,
                      width =5,
                      padx=5,
                      pady=5,
                      text=' ')
           l.grid(row=r+1,column=c)
    #labels中填充日历
    for i in range(len(mo)):
        labels.append(mo[i])
    #数据填充到页面
    for r in range(len(labels)):
        for c in range(7):
           text = labels[r][c]
           if labels[r][c] == 0:
               text = '  '
           l = tk.Label(root,
                      width =5,
                      padx=5,
                      pady=5,
                      text=text)
           l.grid(row=r+1,column=c)

# button：上一月
def ButtonPrevious():
    global Year, Month
    Month -= 1
    if Month < 1:
        Month+= 12
        Year -= 1
    LabelCal(Year, Month)


# button：下一月
def ButtonNext():
    global Year,Month
    Month += 1
    if Month >12:
        Month -= 12
        Year +=1
    LabelCal(Year, Month)

# 默认日期
Year, Month = 2022, 3
LabelCal(Year, Month)

b1 = tk.Button(root,text='上一月',command = ButtonPrevious)
b1.grid(row=8,column=0)

b2 = tk.Button(root,text='下一月',command = ButtonNext)
b2.grid(row=8,column=6)
root.title('第一个tkinter程序')
root.geometry('350x300')
root.resizable(width=False,height=True)
root.mainloop()
